package com.jy.oms.framework.asyn.task.core;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.function.Supplier;

/**
 * 获取RedissonClient原始对象
 *
 * @author liuquan
 * @see com.jy.scm.framework.common.cache.RedisFactory
 * @see com.jy.scm.framework.common.cache.RedissonClientAspect
 * @see com.jy.framework.boot.cache.RedissonFactory
 * @see com.jy.framework.boot.cache.RedissonClientAspect
 */
public class RedissonClientProxy {
    private static RedissonClient redissonClient;

    public static RedissonClient getRedissonClient() {
        return redissonClient;
    }

    public static void setRedissonClient(RedissonClient redissonClient) {
        if (RedissonClientProxy.redissonClient == null) {
            RedissonClientProxy.redissonClient = redissonClient;
        }
    }

    public static <T> T lock(String lockKey, Supplier<T> supplier) {
        RedissonClient redissonClient = RedissonClientProxy.getRedissonClient();
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock();
            return supplier.get();
        } finally {
            lock.unlock();
        }
    }
}
